// ==========================================================================
// gin-sns自动生成控制器相关代码，只生成一次，按需修改,再次生成不会覆盖.
// date：2021-02-21 13:45:54 +0800 CST
// path: app/controller/module/images_api.go
// author：jon
// ==========================================================================
package module

import (
	"gin-sns/app/common/oss"
	"gin-sns/app/ginframe/response"
	"gin-sns/app/ginframe/tools"
	"gin-sns/app/model"
	imagesModel "gin-sns/app/model/module/images"
	"gin-sns/app/service/module"
	"io/ioutil"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	//"gin-sns/app/ginframe/utils/gconv"
)

const uploadMaxBytes int64 = 1024 * 1024 * 3 // 1M

var ImagesApi = newImagesApi()

func newImagesApi() *imagesApi {
	return &imagesApi{}
}

type imagesApi struct {
}

//列表分页数据
func (c *imagesApi) ListAjax(ctx *gin.Context) {
	req := new(imagesModel.SelectPageReq)
	//获取参数
	if err := ctx.ShouldBind(req); err != nil {
		response.ErrorResp(ctx).SetMsg(err.Error()).Log("images管理", req).WriteJsonExit()
		return
	}
	rows := make([]imagesModel.Entity, 0)
	result, page, err := module.ImagesService.SelectListByPage(req)

	if err == nil && len(result) > 0 {
		rows = result
	}

	response.BuildTable(ctx, page.Total, rows).WriteJsonExit()
}

//新增页面保存
func (c *imagesApi) AddSave(ctx *gin.Context) {
	req := new(imagesModel.AddReq)
	//获取参数
	if err := ctx.ShouldBind(req); err != nil {
		response.ErrorResp(ctx).SetBtype(model.Buniss_Add).SetMsg(err.Error()).Log("图片新增数据", req).WriteJsonExit()
		return
	}

	id, err := module.ImagesService.AddSave(req, ctx)

	if err != nil || id <= 0 {
		response.ErrorResp(ctx).SetBtype(model.Buniss_Add).Log("图片新增数据", req).WriteJsonExit()
		return
	}
	response.SucessResp(ctx).SetData(id).Log("图片新增数据", req).WriteJsonExit()
}

//修改页面保存
func (c *imagesApi) EditSave(ctx *gin.Context) {
	req := new(imagesModel.EditReq)
	//获取参数
	if err := ctx.ShouldBind(req); err != nil {
		response.ErrorResp(ctx).SetBtype(model.Buniss_Edit).SetMsg(err.Error()).Log("图片修改数据", req).WriteJsonExit()
		return
	}

	rs, err := module.ImagesService.EditSave(req, ctx)

	if err != nil || rs <= 0 {
		response.ErrorResp(ctx).SetBtype(model.Buniss_Edit).Log("图片修改数据", req).WriteJsonExit()
		return
	}
	response.SucessResp(ctx).SetBtype(model.Buniss_Edit).Log("图片修改数据", req).WriteJsonExit()
}

//删除数据
func (c *imagesApi) Remove(ctx *gin.Context) {
	req := new(model.RemoveReq)
	//获取参数
	if err := ctx.ShouldBind(req); err != nil {
		response.ErrorResp(ctx).SetBtype(model.Buniss_Del).SetMsg(err.Error()).Log("图片删除数据", req).WriteJsonExit()
		return
	}

	rs := module.ImagesService.DeleteRecordByIds(req.Ids)

	if rs > 0 {
		response.SucessResp(ctx).SetBtype(model.Buniss_Del).Log("图片删除数据", req).WriteJsonExit()
	} else {
		response.ErrorResp(ctx).SetBtype(model.Buniss_Del).Log("图片删除数据", req).WriteJsonExit()
	}
}

func PostUpload(c *gin.Context) {
	user := module.UsertokenService.GetCurrent(c)
	if user == nil {
		response.ErrorResp(c).SetMsg(tools.ErrorNotLogin.Error()).WriteJsonExit()
		return
	}

	file, header, err := c.Request.FormFile("image") //todo
	if err != nil {
		response.ErrorResp(c).SetMsg(err.Error()).WriteJsonExit()
		return
	}
	defer file.Close()

	if header.Size > uploadMaxBytes {
		response.ErrorResp(c).SetMsg("图片不能超过3M").WriteJsonExit()
		return
	}

	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		response.ErrorResp(c).SetMsg(err.Error()).WriteJsonExit()
		return
	}

	logrus.Info("上传文件：", header.Filename, " size:", header.Size)

	url, err := oss.PutImage(fileBytes)
	if err != nil {
		response.ErrorResp(c).SetMsg(err.Error()).WriteJsonExit()
		return
	}
	response.ErrorResp(c).SetData(url).WriteJsonExit() //Put("url", url
}

// vditor上传
func PostEditor(c *gin.Context) {
	errFiles := make([]string, 0)
	succMap := make(map[string]string)

	user := module.UsertokenService.GetCurrent(c)
	if user == nil {

		return
	}

	// 限制表单上传大小8MB，默认为32MB
	maxSize := gin.Default().MaxMultipartMemory //check it
	err := c.Request.ParseMultipartForm(maxSize)
	if err != nil {
		//500 = ? StatusInternalServerError
		response.ErrorResp(c).SetMsg(err.Error()).SetCode(500).WriteJsonExit()
		return
	}

	form := c.Request.MultipartForm
	files := form.File["file[]"]
	for _, file := range files {
		f, err := file.Open()
		if err != nil {
			logrus.Error(err)
			errFiles = append(errFiles, file.Filename)
			continue
		}
		fileBytes, err := ioutil.ReadAll(f)
		if err != nil {
			logrus.Error(err)
			errFiles = append(errFiles, file.Filename)
			continue
		}
		url, err := oss.PutImage(fileBytes)
		if err != nil {
			logrus.Error(err)
			errFiles = append(errFiles, file.Filename)
			continue
		}

		succMap[file.Filename] = url
	}

	return

}

// vditor 拷贝第三方图片
func PostFetch(c *gin.Context) {
	user := module.UsertokenService.GetCurrent(c)
	if user == nil {

		return
	}

	var data map[string]string
	data = make(map[string]string)

	//获取参数
	if err := c.ShouldBind(data); err != nil {
		response.ErrorResp(c).SetMsg(err.Error()).Log("oss", data).WriteJsonExit()
		return
	}

	url := data["url"]
	output, err := oss.CopyImage(url)
	if err != nil {

		response.ErrorResp(c).SetMsg(err.Error()).Log("oss", data).WriteJsonExit()
		return
	}

	response.SucessResp(c).SetData(gin.H{"originalURL": url, "url": output}).WriteJsonExit()
	return

}
